const { baseUrl } = require('../config/index.js')

// 封装一个 get 请求
function xhlGet(url, data = {}, title = '加载数据 ^_^') {
  wx.showLoading({
    title: title,
  })

  const p = new Promise((resolve, reject) => {
    wx.request({
      url: baseUrl + url,
      data: data,
      success: (res) => {
        resolve(res.data)
      },
      fail: (err) => {
        reject(err)
      },
      complete: () => {
        wx.hideLoading()
      }
    })
  })

  return p
}

// 封装一个 delete 请求
function xhlDelete(url, id) {
  wx.showLoading({
    title: '正在删除 ^_^',
  })

  const p = new Promise((resolve, reject) => {
    wx.request({
      url: baseUrl + url + '/' + id, // http://localhost:3000/goods
      method: 'DELETE',
      success: (res) => {
        resolve(res.data)
      },
      fail: (err) => {
        reject(err)
      },
      complete: () => {
        wx.hideLoading()
      }
    })
  })

  return p
}

// 封装一个 post 请求
function xhlPost(url, data = {}, title = '正在提交 ^_^') {
  wx.showLoading({
    title: title,
  })

  const p = new Promise((resolve, reject) => {
    wx.request({
      url: baseUrl + url,
      method: 'POST',
      data: data,
      success: (res) => {
        resolve(res.data)
      },
      fail: (err) => {
        reject(err)
      },
      complete: () => {
        wx.hideLoading()
      }
    })
  })

  return p
}

// 封装一个 patch 请求
function xhlPatch(url, data = {}, title = '正在提交 ^_^') {
  wx.showLoading({
    title: title,
  })

  const p = new Promise((resolve, reject) => {
    wx.request({
      url: baseUrl + url,
      method: 'PATCH',
      data: data,
      success: (res) => {
        resolve(res.data)
      },
      fail: (err) => {
        reject(err)
      },
      complete: () => {
        wx.hideLoading()
      }
    })
  })

  return p
}




module.exports = {
  xhlGet,
  xhlDelete,
  xhlPost,
  xhlPatch
}